package com.bhh.myservlet.requestandresponse;

import com.bhh.myservlet.HttpStatus;
import com.bhh.myservlet.Util;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.util.Locale;

/**
 * @author bhh
 * @description 实现Response
 * <p>
 * 实现资源返回
 * <p>
 * 格式 : HTTP/1.1 200 OK
 * @date Created in 2021-04-15 9:06
 * @modified By
 */
@Slf4j
public class NIOResponse implements ServletResponse {
    private static final int BUFFER_SIZE = 1024;
    private static final String NotFoundHtml = "404.html";

    private NIORequest request;
    private SocketChannel channel;
    private ByteBuffer buffer;

    public NIOResponse(SocketChannel channel) {
        this.channel = channel;
        buffer = ByteBuffer.allocate(BUFFER_SIZE);
    }

    public NIORequest getRequest() {
        return request;
    }

    public void setRequest(NIORequest request) {
        this.request = request;
    }

    /**
     * 返回静态资源
     * 获取请求资源在本地的路径
     * 根据本地路劲获取文件
     * 将文件写入流中
     * 进行返回
     */
    public void sendStaticResource() throws IOException {
        /*
        应当是在处理request阶段就已经进行了处理, 无需再调用parse()进行解析
        try {
            request.parse();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        // 获取本地文件
        File file = new File(Util.WEB_ROOT, request.getUri());
        System.out.println(file.getPath());
        try {
            write(file, HttpStatus.RE_OK);
        } catch (IOException e) {
            // 若是发生异常, 则返回404页面
            write(new File(NotFoundHtml), HttpStatus.RE_NOTFOUND);
        }
    }

    private void write(File file, HttpStatus status) throws IOException {

        // 获取文件 channel
        FileChannel fileChannel = new FileInputStream(file).getChannel();

        // 转换为写模式
        buffer.clear();
        // 先将响应头写入buffer
        buffer.put(Util.renderStatus(status).getBytes());
        // 再读取文件, 将文件写入buffer
        int read = 0;
        while((read = fileChannel.read(buffer)) != -1){
            buffer.flip();
            while (buffer.hasRemaining()){
                channel.write(buffer);
            }
            buffer.clear();
        }
    }

    @Override
    public String getCharacterEncoding() {
        return null;
    }

    @Override
    public String getContentType() {
        return null;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return null;
    }

    /**
     * 可以在servlet中将数据方便的写入outputStream中
     * write 调用 println() 方法来进行写入 流
     * @return
     * @throws IOException
     */
    @Override
    public PrintWriter getWriter() throws IOException {
        // 参数一 : OutputStream流
        // 参数二 : 是否自动刷新
        PrintWriter writer = new PrintWriter(channel.socket().getOutputStream(), true);
        return writer;
    }

    @Override
    public void setCharacterEncoding(String charset) {

    }

    @Override
    public void setContentLength(int len) {

    }

    @Override
    public void setContentType(String type) {

    }

    @Override
    public void setBufferSize(int size) {

    }

    @Override
    public int getBufferSize() {
        return 0;
    }

    @Override
    public void flushBuffer() throws IOException {

    }

    @Override
    public void resetBuffer() {

    }

    @Override
    public boolean isCommitted() {
        return false;
    }

    @Override
    public void reset() {

    }

    @Override
    public void setLocale(Locale loc) {

    }

    @Override
    public Locale getLocale() {
        return null;
    }
}
